package com.example.zbh.dsliao.ui.adapter;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.FileMessageBody;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.NormalFileMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VideoMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.easemob.util.DateUtils;
import com.easemob.util.ImageUtils;
import com.easemob.util.TextFormater;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.application.App;
import com.example.zbh.dsliao.constant.Constant;
import com.example.zbh.dsliao.db.DatabaseHelper;
import com.example.zbh.dsliao.db.entity.UserContact;
import com.example.zbh.dsliao.utils.DliaoImageCache;
import com.example.zbh.dsliao.utils.DliaoUtils;
import com.example.zbh.dsliao.utils.PreferenceHelper;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by zbh on 15/11/24.
 */
public class GroupChatAdapter extends BaseAdapter {
    private List<EMMessage> list;
    private Context context;
    private ImageMessageBody imageBody;
    private AssetManager manager;
    private Typeface typeface;

    public GroupChatAdapter(Context context) {
        this.context = context;
        manager = context.getAssets();
    }

    public void addData(List<EMMessage> list, String name) {
        this.list = list;
        notifyDataSetChanged();
    }

    public boolean isLength() {
        return list != null && list.size() > 0;
    }


    @Override
    public int getCount() {
        return isLength() ? list.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_chat_gut, null);
        } else {
            view = convertView;
        }
        ViewHolder holder = ViewHolder.getHolder(view);
        final EMMessage message = list.get(position);
        Log.i("nannannan", message.toString());
        final String MsgId = message.getMsgId();
        //设置每条消息的时间
        long time = message.getMsgTime();
        String chattime = getNormalTime(time + "");
        //设置聊天字体的属性


        if (chattime != null) {
            holder.chatTimeTv.setVisibility(View.VISIBLE);
            holder.chatTimeTv.setText(chattime);
        }


        if (message.direct == EMMessage.Direct.RECEIVE) {//接受者---左
            holder.usernameLeftTv.setVisibility(View.VISIBLE);
            holder.usernameLeftTv.setText(message.getFrom());
            UserContact userContact = DatabaseHelper.getInstance().queryContactPeopleByName(message.getFrom());
            if (userContact != null){
                String avater = userContact.getAvatar();
                if (avater != null){
                    holder.avaterLeft.setVisibility(View.VISIBLE);
                    Glide.with(context)
                            .load(avater)
                            .placeholder(R.drawable.dl_default_avatar)
                            .error(R.drawable.dl_default_avatar)
                            .into(holder.avaterLeft);
                }
            }else {
            holder.avaterLeft.setVisibility(View.VISIBLE);
            }
            holder.avaterRight.setVisibility(View.GONE);
            holder.left_layout.setVisibility(View.VISIBLE);
            holder.right_layout.setVisibility(View.GONE);
            holder.left_msg.setVisibility(View.GONE);
            holder.left_pic.setVisibility(View.GONE);
            holder.voice_right.setVisibility(View.GONE);
            holder.voice_left.setVisibility(View.GONE);
            holder.left_file_lin.setVisibility(View.GONE);
            holder.right_file_lin.setVisibility(View.GONE);
            holder.left_video_rel.setVisibility(View.GONE);
            holder.right_video_rel.setVisibility(View.GONE);

            switch (message.getType()) {
                case TXT:
                    TextMessageBody body = (TextMessageBody) message.getBody();
                    String text = body.getMessage();
                    CharSequence cs = Html.fromHtml(text, imageGetter, null);

                    holder.left_msg.setVisibility(View.VISIBLE);
                    setHolderText(holder.left_msg);

                    holder.left_msg.setText(cs);
                    break;
                case IMAGE:
                    holder.left_pic.setVisibility(View.VISIBLE);
                    setUpPic(message, holder.left_pic);
                    break;
                case VIDEO:
                    holder.left_video_rel.setVisibility(View.VISIBLE);
                    VideoMessageBody videoMessageBody = (VideoMessageBody) message.getBody();
                    String localThumb = videoMessageBody.getLocalThumb();
                    if (localThumb != null) {
                        showVideoThumbView(localThumb, holder.left_chatting_content_iv, videoMessageBody.getThumbnailUrl(), message);
                    }
                    if (videoMessageBody.getLength() > 0) {
                        String videoTime = DateUtils.toTimeBySecond(videoMessageBody.getLength());
                        holder.left_chatting_length_iv.setText(videoTime);
                    }
                    if (videoMessageBody.getVideoFileLength() > 0) {
                        String videoSize = TextFormater.getDataSize(videoMessageBody.getVideoFileLength());
                        holder.left_chatting_size_iv.setText(videoSize);
                    }
                    if (message.status == EMMessage.Status.INPROGRESS) {
                        holder.left_chatting_content_iv.setImageResource(R.mipmap.dl_default_image);
                    } else {
                        holder.left_chatting_content_iv.setImageResource(R.mipmap.dl_default_image);
                        showVideoThumbView(localThumb, holder.left_chatting_content_iv, videoMessageBody.getThumbnailUrl(), message);
                    }
                    holder.left_video_rel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (videoClickListener != null) {
                                videoClickListener.onShowVideoClick(message);
                            }
                        }
                    });


                    break;
                case LOCATION:
                    break;
                case VOICE:
                    holder.voice_left.setVisibility(View.VISIBLE);
                    VoiceMessageBody voiceMessageBody = (VoiceMessageBody) message.getBody();
                    final String fileName = voiceMessageBody.getLocalUrl();
                    holder.voice_left.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (voiceListener != null) {
                                voiceListener.OnVoiceClick(fileName);
                            }
                        }
                    });
                    break;
                case FILE:
                    holder.left_file_lin.setVisibility(View.VISIBLE);
                    NormalFileMessageBody fileMessageBody = (NormalFileMessageBody) message.getBody();
                    String filePath = fileMessageBody.getLocalUrl();
                    //赋值
                    holder.left_file_name.setText(fileMessageBody.getFileName());
                    holder.left_file_size.setText(TextFormater.getDataSize(fileMessageBody.getFileSize()));
                    File file = new File(filePath);
                    if (file != null && file.exists()) {
                        holder.left_file_status.setText("已下载");
                    } else {
                        holder.left_file_status.setText("未下载");
                    }
                    holder.left_file_lin.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (fileListener != null) {
                                fileListener.onFileClick(message);
                            }

                        }
                    });


                    break;
                case CMD:
                    break;
            }


        } else {//发送者--右
            holder.usernameLeftTv.setVisibility(View.GONE);
            holder.avaterRight.setVisibility(View.VISIBLE);
            Glide.with(context)
                    .load(PreferenceHelper.getInstance().getThreeCurrentUserAvatar())
                    .placeholder(R.drawable.dl_default_avatar)
                    .error(R.drawable.dl_default_avatar)
                    .into(holder.avaterRight);
            holder.avaterLeft.setVisibility(View.GONE);
            holder.left_layout.setVisibility(View.GONE);
            holder.right_layout.setVisibility(View.VISIBLE);
            holder.right_msg.setVisibility(View.GONE);
            holder.right_pic.setVisibility(View.GONE);
            holder.voice_right.setVisibility(View.GONE);
            holder.voice_left.setVisibility(View.GONE);
            holder.left_file_lin.setVisibility(View.GONE);
            holder.right_file_lin.setVisibility(View.GONE);
            holder.left_video_rel.setVisibility(View.GONE);
            holder.right_video_rel.setVisibility(View.GONE);


            switch (message.getType()) {
                case TXT:
                    TextMessageBody body = (TextMessageBody) message.getBody();
                    String text = body.getMessage();
                    Log.i("sssss", text);
                    CharSequence cs = Html.fromHtml(text, imageGetter, null);
                    holder.right_msg.setVisibility(View.VISIBLE);
                    setHolderText(holder.right_msg);
                    holder.right_msg.setText(cs);
                    break;
                case IMAGE:
                    holder.right_pic.setVisibility(View.VISIBLE);
                    setUpPic(message, holder.right_pic);
                    break;
                case VIDEO:
                    holder.right_video_rel.setVisibility(View.VISIBLE);
                    VideoMessageBody videoMessageBody = (VideoMessageBody) message.getBody();
                    String localThumb = videoMessageBody.getLocalThumb();
                    if (localThumb != null) {
                        showVideoThumbView(localThumb, holder.right_chatting_content_iv, videoMessageBody.getThumbnailUrl(), message);
                    }
                    if (videoMessageBody.getLength() > 0) {
                        String videoTime = DateUtils.toTimeBySecond(videoMessageBody.getLength());
                        holder.right_chatting_length_iv.setText(videoTime);
                    }
                    if (videoMessageBody.getLocalUrl() != null && new File(videoMessageBody.getLocalUrl()).exists()) {
                        String videoSize = TextFormater.getDataSize(videoMessageBody.getVideoFileLength());
                        holder.right_chatting_size_iv.setText(videoSize);
                    }
                    holder.right_video_rel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (videoClickListener != null) {
                                videoClickListener.onShowVideoClick(message);
                            }
                        }
                    });

                    break;
                case LOCATION:
                    break;
                case VOICE:
                    holder.voice_right.setVisibility(View.VISIBLE);
                    VoiceMessageBody voiceMessageBody = (VoiceMessageBody) message.getBody();
                    final String fileName = voiceMessageBody.getLocalUrl();
                    final int len = voiceMessageBody.getLength();
                    holder.voice_right.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (voiceListener != null) {
                                Log.i("sssddddd", len + "");
                                voiceListener.OnVoiceClick(fileName);
                            }
                        }
                    });
                    break;
                case FILE:
                    holder.right_file_lin.setVisibility(View.VISIBLE);
                    NormalFileMessageBody fileMessageBody = (NormalFileMessageBody) message.getBody();
                    String filePath = fileMessageBody.getLocalUrl();
                    //赋值
                    holder.right_file_name.setText(fileMessageBody.getFileName());
                    holder.right_file_size.setText(TextFormater.getDataSize(fileMessageBody.getFileSize()));
                    holder.right_file_lin.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (fileListener != null) {
                                fileListener.onFileClick(message);
                            }
                        }
                    });

                    break;
                case CMD:
                    break;
            }
        }
        //长按一整条消息的行布局
        holder.chatOnelayout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (onItemChatOneLongClickListener != null) {
                    onItemChatOneLongClickListener.OnChatOneLongClick(v, MsgId);
                }
                return true;
            }
        });
        return view;
    }

    //设置聊天字体属性
    private void setHolderText(TextView holderText) {
        String textType = PreferenceHelper.getInstance().getCurrentTextType();
        String textColor = PreferenceHelper.getInstance().getCurrentuserTextColor();
        String textSize = PreferenceHelper.getInstance().getCurrentTextSize();
        if (textType != null) {
            switch (textType) {
                case Constant.TYPE_01:
                    typeface = Typeface.createFromAsset(manager, "xindixiaowanzi.ttf");
                    holderText.setTypeface(typeface);
                    break;
                case Constant.TYPE_02:
                    typeface = Typeface.createFromAsset(manager, "xindiwenguimingti.ttf");
                    holderText.setTypeface(typeface);
                    break;
                case Constant.TYPE_03:
                    typeface = Typeface.DEFAULT;
                    holderText.setTypeface(typeface);
                    break;
            }
        }
        if (textColor != null) {
            switch (textColor) {
                case Constant.COLOR_01:
                    int colorb = Constant.COLOR_BLACK;
                    holderText.setTextColor(colorb);
                    break;
                case Constant.COLOR_02:
                    int colorw = Constant.COLOR_WHITE;
                    holderText.setTextColor(colorw);
                    break;
                case Constant.COLOR_03:
                    int colorr = Constant.COLOR_GREEN;
                    holderText.setTextColor(colorr);
                    break;
                case Constant.COLOR_04:
                    int colorg = Constant.COLOR_RED;
                    holderText.setTextColor(colorg);
                    break;
            }
        }
        if (textSize != null) {
            switch (textSize) {
                case Constant.SIZE_01:
                    float l = Constant.SIZE_LARGE;
                    holderText.setTextSize(l);
                    break;
                case Constant.SIZE_02:
                    float m = Constant.SIZE_MIDDLE;
                    holderText.setTextSize(m);
                    break;
                case Constant.SIZE_03:
                    float s = Constant.SIZE_SMALL;
                    holderText.setTextSize(s);
                    break;
            }
        }

    }

    //设置图片
    private void setUpPic(EMMessage message, ImageView imageView) {
        imageBody = (ImageMessageBody) message.getBody();
        if (message.direct == EMMessage.Direct.RECEIVE) {
            if (message.status == EMMessage.Status.INPROGRESS) {
                imageView.setImageResource(R.mipmap.ic_launcher);

            } else {
                imageView.setImageResource(R.mipmap.ic_launcher);
                if (imageBody.getLocalUrl() != null) {
                    // String filePath = imgBody.getLocalUrl();
                    String remotePath = imageBody.getRemoteUrl();
                    String filePath = DliaoUtils.getImagePath(remotePath);
                    String thumbRemoteUrl = imageBody.getThumbnailUrl();
                    String thumbnailPath = DliaoUtils.getThumbnailImagePath(thumbRemoteUrl);
                    showImageView(thumbnailPath, imageView, filePath, message);
                }
            }
            return;
        }
        String filePath = imageBody.getLocalUrl();
        if (filePath != null) {
            showImageView(DliaoUtils.getThumbnailImagePath(filePath), imageView, filePath, message);
        }

    }

    //展示
    private boolean showImageView(final String thumbernailPath, final ImageView iv, final String localFullSizePath, final EMMessage message) {
        Bitmap bitmap = DliaoImageCache.getInstance().get(thumbernailPath);
        if (bitmap != null) {
            // thumbnail image is already loaded, reuse the drawable
            iv.setImageBitmap(bitmap);
            return true;
        } else {
            new AsyncTask<Object, Void, Bitmap>() {

                @Override
                protected Bitmap doInBackground(Object... args) {
                    File file = new File(thumbernailPath);
                    if (file.exists()) {
                        return DliaoUtils.decodeScaleImage(thumbernailPath, 160, 160);
                    } else {
                        if (message.direct == EMMessage.Direct.SEND) {
                            return DliaoUtils.decodeScaleImage(localFullSizePath, 160, 160);
                        } else {
                            return null;
                        }
                    }
                }

                protected void onPostExecute(Bitmap image) {
                    if (image != null) {
                        iv.setImageBitmap(image);
                        DliaoImageCache.getInstance().put(thumbernailPath, image);
                    } else {
                        if (message.status == EMMessage.Status.FAIL) {
                            if (DliaoUtils.isNetWorkConnected(App.getContext())) {
                                new Thread(new Runnable() {

                                    @Override
                                    public void run() {
                                        EMChatManager.getInstance().asyncFetchMessage(message);
                                    }
                                }).start();
                            }
                        }

                    }
                }
            }.execute();

            return true;
        }


    }

    /**
     * 时间格式转换
     **/
    public String getNormalTime(String value) {
        Long l = Long.valueOf(value);
//        l = l * 1000;
        Date date = new Date(l);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        return time;
    }


    public static class ViewHolder {
        private TextView left_msg, right_msg, chatTimeTv, left_file_name, right_file_name, left_file_size, right_file_size,
                left_file_status, right_file_status, right_chatting_size_iv, left_chatting_size_iv,
                left_chatting_length_iv, right_chatting_length_iv, usernameLeftTv;
        private LinearLayout left_layout, right_layout, chatOnelayout, left_file_lin, right_file_lin, voice_right, voice_left;//一条会话的整体布局;
        private ImageView avaterLeft, avaterRight, right_pic, left_pic, right_chatting_content_iv, left_chatting_content_iv,
                right_chatting_status_btn, left_chatting_status_btn;
        private RelativeLayout left_video_rel, right_video_rel;

        public static ViewHolder getHolder(View view) {
            ViewHolder holder = (ViewHolder) view.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.left_msg = (TextView) view.findViewById(R.id.left_msg);
                holder.right_msg = (TextView) view.findViewById(R.id.right_msg);
                holder.left_layout = (LinearLayout) view.findViewById(R.id.left_layout);
                holder.right_layout = (LinearLayout) view.findViewById(R.id.right_layout);
                holder.avaterRight = (ImageView) view.findViewById(R.id.avaterRight);
                holder.avaterLeft = (ImageView) view.findViewById(R.id.avaterLeft);
                holder.chatTimeTv = (TextView) view.findViewById(R.id.chatTimeTv);
                holder.left_pic = (ImageView) view.findViewById(R.id.left_pic);
                holder.right_pic = (ImageView) view.findViewById(R.id.right_pic);
                holder.chatOnelayout = (LinearLayout) view.findViewById(R.id.chatOnelayout);
                holder.voice_right = (LinearLayout) view.findViewById(R.id.voice_right);
                holder.voice_left = (LinearLayout) view.findViewById(R.id.voice_left);
                holder.left_file_lin = (LinearLayout) view.findViewById(R.id.left_file_lin);
                holder.right_file_lin = (LinearLayout) view.findViewById(R.id.right_file_lin);
                holder.left_file_name = (TextView) view.findViewById(R.id.left_file_name);
                holder.right_file_name = (TextView) view.findViewById(R.id.right_file_name);
                holder.left_file_size = (TextView) view.findViewById(R.id.left_file_size);
                holder.right_file_size = (TextView) view.findViewById(R.id.right_file_size);
                holder.left_file_status = (TextView) view.findViewById(R.id.left_file_status);
                holder.right_file_status = (TextView) view.findViewById(R.id.right_file_status);
                holder.left_video_rel = (RelativeLayout) view.findViewById(R.id.left_video_rel);
                holder.right_video_rel = (RelativeLayout) view.findViewById(R.id.right_video_rel);
                holder.left_chatting_content_iv = (ImageView) view.findViewById(R.id.left_chatting_content_iv);
                holder.right_chatting_content_iv = (ImageView) view.findViewById(R.id.right_chatting_content_iv);
                holder.right_chatting_size_iv = (TextView) view.findViewById(R.id.right_chatting_size_iv);
                holder.left_chatting_size_iv = (TextView) view.findViewById(R.id.left_chatting_size_iv);
                holder.left_chatting_length_iv = (TextView) view.findViewById(R.id.left_chatting_length_iv);
                holder.right_chatting_length_iv = (TextView) view.findViewById(R.id.right_chatting_length_iv);
                holder.right_chatting_status_btn = (ImageView) view.findViewById(R.id.right_chatting_status_btn);
                holder.left_chatting_status_btn = (ImageView) view.findViewById(R.id.right_chatting_status_btn);
                holder.usernameLeftTv = (TextView) view.findViewById(R.id.usernameLeftTv);

            }
            return holder;
        }
    }

    private Html.ImageGetter imageGetter = new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
            int id = Integer.parseInt(source);
            Drawable drawable = context.getResources().getDrawable(id);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            return drawable;
        }
    };

    /**
     * 展示视频缩略图
     *
     * @param localThumb   本地缩略图路径
     * @param iv
     * @param thumbnailUrl 远程缩略图路径
     * @param message
     */
    private void showVideoThumbView(final String localThumb, final ImageView iv, String thumbnailUrl, final EMMessage message) {
        // first check if the thumbnail image already loaded into cache
        Bitmap bitmap = DliaoImageCache.getInstance().get(localThumb);
        if (bitmap != null) {
            // thumbnail image is already loaded, reuse the drawable
            iv.setImageBitmap(bitmap);

        } else {
            new AsyncTask<Void, Void, Bitmap>() {

                @Override
                protected Bitmap doInBackground(Void... params) {
                    if (new File(localThumb).exists()) {
                        return ImageUtils.decodeScaleImage(localThumb, 160, 160);
                    } else {
                        return null;
                    }
                }

                @Override
                protected void onPostExecute(Bitmap result) {
                    super.onPostExecute(result);
                    if (result != null) {
                        DliaoImageCache.getInstance().put(localThumb, result);
                        iv.setImageBitmap(result);

                    } else {
                        if (message.status == EMMessage.Status.FAIL) {
                            if (DliaoUtils.isNetWorkConnected(context)) {
                                EMChatManager.getInstance().asyncFetchMessage(message);
                            }
                        }

                    }
                }
            }.execute();
        }

    }

    /**
     * 长按一条消息的接口毁掉
     **/
    private OnItemChatOneLongClickListener onItemChatOneLongClickListener;

    public void setOnItemChatOneLongClickListener(OnItemChatOneLongClickListener onItemChatOneLongClickListener) {
        this.onItemChatOneLongClickListener = onItemChatOneLongClickListener;
    }

    public interface OnItemChatOneLongClickListener {
        void OnChatOneLongClick(View view, String MsgId);
    }

    //语音
    public interface OnVoiceClickListener {
        void OnVoiceClick(String name);
    }

    private OnVoiceClickListener voiceListener;

    public void setOnVoiceClickListener(OnVoiceClickListener voiceListener) {
        this.voiceListener = voiceListener;
    }

    //下载文件
    public interface OnFileClickListener {
        void onFileClick(EMMessage message);
    }

    private OnFileClickListener fileListener;

    public void setOnFileClickListener(OnFileClickListener fileListener) {
        this.fileListener = fileListener;
    }

    public interface OnShowVideoClickListener {
        void onShowVideoClick(EMMessage message);
    }

    private OnShowVideoClickListener videoClickListener;

    public void setOnShowVideoClickListener(OnShowVideoClickListener videoClickListener) {
        this.videoClickListener = videoClickListener;
    }


}
